package com.lsb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsb.mapper.UserMapper;
import com.lsb.pojo.Submit;
import com.lsb.mapper.SubmitMapper;
import com.lsb.pojo.User;
import com.lsb.response.Result;
import com.lsb.service.SubmitService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsb.utils.MyJsonUtils;
import com.lsb.vo.ChartVO;
import com.lsb.vo.SubmitVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liusibo
 * @since 2021-06-10
 */
@Service
public class SubmitServiceImpl extends ServiceImpl<SubmitMapper, Submit> implements SubmitService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    SubmitMapper submitMapper;

    //每天凌晨3点定时执行该方法，插入所有用户第二天的打卡记录
    @Scheduled(cron = "0 0 3 * * *")
    @Override
    public void insertData() {
        //获取当前系统时间的后一天的时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date date=new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, +1);
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        date = calendar.getTime();
        System.out.println(sdf.format(date));

        Date finalDate = date;
        Date finalDate1 = date;

        List<User> userList = userMapper.selectList(new QueryWrapper<>());
        userList.forEach(user -> {
            //构建一个submit记录
            Submit submit = new Submit(user.getId(),user.getUsername(),
                    user.getRealName(),user.getTelephoneNumber(),user.getIdentityNumber(),
                    finalDate, finalDate1
            );
            //向数据库表中插入该条记录
            submitMapper.insert(submit);
        });
    }

    @Override
    public void getTodaySubmit(HttpServletResponse response) throws IOException, ServletException {
        List<Submit> submitList = submitMapper.selectList(new QueryWrapper<>());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        //显示给前端的打卡数据submitVO
        List<SubmitVO> submitVOList = new ArrayList<>();
        //过滤日期不是今天的健康打卡数据
        List<Submit> collect = submitList.stream().filter(submit -> {
            boolean equals = sdf.format(submit.getCreateTime()).equals(sdf.format(new Date()));
            return equals;
        }).collect(Collectors.toList());
        //装入SubmitVO给前端回显打卡数据
        collect.forEach(submit -> submitVOList.add(new SubmitVO(
                submit.getUserId(),submit.getUsername(),submit.getRealName()
                ,submit.getTelephoneNumber(),submit.getIdentityNumber()
                ,submit.getTemperature(),sdf.format(submit.getCreateTime())
                ,submit.getIsSubmit()==1?"已提交":"未提交"
        )));
        //返回json格式数据给前端
        Result result = Result.ok().message("今日打卡数据").data("todaySubmitData",submitVOList);
        MyJsonUtils.WriteJSON(response,result);
    }

    @Override
    public void getAllSubmit(HttpServletResponse response) throws IOException, ServletException {
        List<Submit> submitList = submitMapper.selectList(new QueryWrapper<>());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        //显示给前端的打卡数据submitVO
        List<SubmitVO> submitVOList = new ArrayList<>();
        //过滤掉第二天的数据,如果存在的话,由于定时任务的原因,有可能已经存在第二天的数据
        List<Submit> collect = submitList.stream().filter(submit -> {
            int i = sdf.format(submit.getCreateTime()).compareTo(sdf.format(new Date()));
            return i <= 0;
        }).collect(Collectors.toList());
        //装入SubmitVO给前端回显打卡数据
        collect.forEach(submit -> submitVOList.add(new SubmitVO(
                submit.getUserId(),submit.getUsername(),submit.getRealName()
                ,submit.getTelephoneNumber(),submit.getIdentityNumber()
                ,submit.getTemperature(),sdf.format(submit.getCreateTime())
                ,submit.getIsSubmit()==1?"已提交":"未提交"
        )));
        //返回json格式数据给前端
        Result result = Result.ok().message("所有打卡数据").data("allSubmitData",submitVOList);
        MyJsonUtils.WriteJSON(response,result);
    }

    @Override
    public void getAbnormalTemperature(List<SubmitVO> submitList, HttpServletResponse response) throws Exception {
        List<SubmitVO> collect = submitList.stream()
                //大于等于37.3摄氏度认为体温异常
                .filter(submit -> submit.getTemperature() >= 37.3)
                .collect(Collectors.toList());
        //返回json格式数据给前端
        Result result = Result.ok().message("异常的体温数据").data("abnormalTemperature",collect);
        MyJsonUtils.WriteJSON(response,result);
    }

    @Override
    public void getUncommitted(List<SubmitVO> submitList, HttpServletResponse response) throws Exception {
        List<SubmitVO> collect = submitList.stream()
                //筛选出未提交的数据
                .filter(submit -> submit.getIsSubmit().equals("未提交"))
                .collect(Collectors.toList());
        //返回json格式数据给前端
        Result result = Result.ok().message("未提交的打卡数据").data("uncommitted",collect);
        MyJsonUtils.WriteJSON(response,result);
    }

    @Override
    public void getDateSubmit(String date, HttpServletResponse response) throws Exception {
        List<Submit> submitList = submitMapper.selectList(new QueryWrapper<>());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        //显示给前端的打卡数据submitVOList
        List<SubmitVO> submitVOList = new ArrayList<>();
        //拿到对应日期的打卡数据
        List<Submit> collect = submitList.stream().filter(submit -> {
            boolean equals = sdf.format(submit.getCreateTime()).equals(date);
            return equals;
        }).collect(Collectors.toList());
        //封装成SubmitVOList给前端回显打卡数据
        collect.forEach(submit -> submitVOList.add(new SubmitVO(
                submit.getUserId(),submit.getUsername(),submit.getRealName()
                ,submit.getTelephoneNumber(),submit.getIdentityNumber()
                ,submit.getTemperature(),sdf.format(submit.getCreateTime())
                ,submit.getIsSubmit()==1?"已提交":"未提交"
        )));
        //返回json格式数据给前端
        Result result = Result.ok().message("根据日期获得的打卡数据").data("dateSubmitData",submitVOList);
        MyJsonUtils.WriteJSON(response,result);
    }

    @Override
    public void getSubmitByUsernameMohu(List<LinkedHashMap> submitVOList, String username, HttpServletResponse response) throws Exception {
        List<LinkedHashMap> collect = submitVOList.stream()
                .filter(map -> {
                    String regex = ".*"+username+".*";
                    return Pattern.matches(regex,map.get("username").toString());
                })
                .collect(Collectors.toList());
        //返回json格式数据给前端
        Result result = Result.ok().message("根据学号模糊查询数据").data("mohuData",collect);
        MyJsonUtils.WriteJSON(response,result);
    }

    @Override
    public void getTodayChart(HttpServletResponse response) throws Exception {
        List<Submit> submitList = submitMapper.selectList(new QueryWrapper<>());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        List<ChartVO> chartVOList = new ArrayList<>();
        //过滤日期不是今天的健康打卡数据
        List<Submit> collect = submitList.stream().filter(submit -> {
            boolean equals = sdf.format(submit.getCreateTime()).equals(sdf.format(new Date()));
            return equals;
        }).collect(Collectors.toList());
        int uncommittedNumber;
        int submitNumber = 0;
        //封装图表所需数据
        uncommittedNumber = (int) collect.stream().filter(submit -> submit.getIsSubmit() == 0).count();
        submitNumber = collect.size()-uncommittedNumber;
        chartVOList.add(0,new ChartVO(submitNumber,"已提交"));
        chartVOList.add(1,new ChartVO(uncommittedNumber,"未提交"));
        //返回json格式数据给前端
        Result result = Result.ok().message("今日打卡图表数据").data("todayChart",chartVOList);
        MyJsonUtils.WriteJSON(response,result);
    }

    @Override
    public void insertRegisterSubmit(User user, int flag) {
        if(flag==1){
            Date date=new Date();
            //插入今天的打卡数据
            Submit submit = new Submit(user.getId(),user.getUsername(),
                    user.getRealName(),user.getTelephoneNumber(),user.getIdentityNumber(),
                    date, date
            );
            //向数据库表中插入该条记录
            submitMapper.insert(submit);
        }
        else if(flag==2){
            Date date=new Date();
            //插入今天的打卡数据
            Submit submit = new Submit(user.getId(),user.getUsername(),
                    user.getRealName(),user.getTelephoneNumber(),user.getIdentityNumber(),
                    date, date
            );
            //向数据库表中插入该条记录
            submitMapper.insert(submit);

            //插入明天的打卡数据
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DATE, +1);
            calendar.set(Calendar.HOUR_OF_DAY,0);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);
            date = calendar.getTime();
            Submit submit2 = new Submit(user.getId(),user.getUsername(),
                    user.getRealName(),user.getTelephoneNumber(),user.getIdentityNumber(),
                    date, date
            );
            //向数据库表中插入该条记录
            submitMapper.insert(submit2);
        }
    }


}
